package com.org.manhu.chargehelper.ui;

import java.text.DecimalFormat;
import java.util.Map;

import com.org.manhu.chargehelper.ChargeApplication;
import com.org.manhu.chargehelper.R;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateMoneyReceiver;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateNickNameReceiver;
import com.org.manhu.chargehelper.constant.Constant;
import com.org.manhu.chargehelper.custom.BatteryCharger;
import com.org.manhu.chargehelper.tools.AppManager;
import com.org.manhu.chargehelper.tools.DeviceInfo;
import com.org.manhu.chargehelper.tools.JsonUtil;
import com.org.manhu.chargehelper.tools.NetUtils;
import com.org.manhu.chargehelper.tools.SharedPreferncesUtil;
import com.org.manhu.chargehelper.tools.ToastUtils;
import com.org.manhu.chargehelper.webservice.AsyncProcessData;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * @文件名：ExchangeActivity.java
 * @包名：com.org.manhu.chargehelper.ui
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年2月5日 下午8:25:53
 *
 * @描述：
 */
public class ExchangeActivity extends Activity implements OnClickListener {

	private ImageView backIv, userInfoMoreIv;
	private Button exchangeBtn, cashOutBtn;
	private TextView goodsNameTxt, goodsPriceTxt, providerTxt, totalPriceTxt;

	private EditText exchangeNumEdt;
	private Button addBtn, reduceBtn, sureBtn, cancleBtn;
	private RelativeLayout userInfo;
	private TextView userNameTv, awardNumTv;
	private BatteryCharger battery;

	private int goodsNum;

	private String[] goodsInfoArray;
	private String goodsId;
	private String goodsName;
	private String goodsPrice;
	private String cp;
	private float price;
	private DecimalFormat df = new DecimalFormat("0.00");

	private AsyncProcessData request;
	private String AuthKey;
	private UpdateNickNameReceiver mReceiver;
	private UpdateMoneyReceiver receivers;

	private String channelId;
	private String devId;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String json = msg.getData().getString("jsonStr");
			if (Constant.CLIENT_INIT.equals(msg.obj.toString())) {
				Map<String, String> map = JsonUtil.parseToMap(json);
				if (map != null) {
					ChargeApplication.updateInitInfo(map);
					userExchange(ChargeApplication.getInitInfo().get("AuthKey"));
				} else {
					clientInit();
				}
			} else if (Constant.SUBMIT_GOODS_ORDER.equals(msg.obj.toString())) {
				Map<String, String> feedBackMap = JsonUtil.parseAll(json);
				if (feedBackMap != null) {
					if (feedBackMap.get("Code").equals("0")) {
						clientInit();
					} else {
						Map<String, String> map = JsonUtil.parseAll(json);
						if (map.get("Code").equals("1")) {
							Intent intent = new Intent();
							intent.setAction(Constant.ACTION_UPDATE_MONEY);
							float nowMoney = Float.parseFloat(awardNumTv
									.getText().toString());
							nowMoney = nowMoney
									- Float.parseFloat(totalPriceTxt.getText()
											.toString());
							intent.putExtra("money", df.format(nowMoney));
							sendBroadcast(intent);
							ExchangeActivity.this.finish();
							SharedPreferncesUtil.saveMoney(
									ExchangeActivity.this, nowMoney);
						}
						ToastUtils.showShort(ExchangeActivity.this,
								map.get("Description"));
					}
				}
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_exchange);
		AppManager.getAppManager().addActivity(this);
		init();
		getData();

		request = new AsyncProcessData();
		AuthKey = ChargeApplication.getInitInfo().get("AuthKey");
		if (TextUtils.isEmpty(AuthKey) || AuthKey == null) {
			clientInit();
		}

		mReceiver = new UpdateNickNameReceiver(userNameTv);
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_NICKNAME);
		registerReceiver(mReceiver, filter);

		receivers = new UpdateMoneyReceiver(awardNumTv);
		IntentFilter filters = new IntentFilter(Constant.ACTION_UPDATE_MONEY);
		registerReceiver(receivers, filters);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		userNameTv.setText(SharedPreferncesUtil.getNickName(this));
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mReceiver);
		unregisterReceiver(receivers);
	}

	/**
	 * @描述： 客户端初始化，获取AuthKey
	 */
	private void clientInit() {
		if (NetUtils.isConnected(this)) {
			if (Constant.IS_USE_BOXINFO) {
				channelId = SharedPreferncesUtil.getBoxInfo(this,
						Constant.SP_BOX_CHANNELID);
				devId = SharedPreferncesUtil.getBoxInfo(this,
						Constant.SP_BOX_DEVID);
			} else {
				channelId = "0";
				devId = "0";
			}
			request.getRequestData(mHandler, Constant.CLIENT_INIT, "AuthKey",
					"", "Imei", DeviceInfo.getIMEI(), "Imsi",
					DeviceInfo.getIMSI(), "AndroidId",
					DeviceInfo.getAndroidID(), "PhoneTypeId",
					DeviceInfo.getDeviceModel(), "ChannelId", channelId,
					"DevId", devId);
		} else {
			ToastUtils.showShort(this, "网络异常，请稍检查网络");
		}
	}

	/**
	 * @描述： 获取上个页面传过来的数据,并将数据显示出来
	 */
	private void getData() {
		String goodsInfo = getIntent().getStringExtra("goodsInfo");
		goodsInfoArray = goodsInfo.split(";");
		goodsId = goodsInfoArray[1].split(":")[1];
		goodsName = goodsInfoArray[2].split(":")[1];
		goodsPrice = goodsInfoArray[3].split(":")[1];
		cp = goodsInfoArray[4].split(":")[1];
		price = Float.parseFloat(goodsPrice.substring(0,
				goodsPrice.length() - 1));
		setData();
	}

	/**
	 * @描述：
	 */
	private void setData() {
		// TODO Auto-generated method stub
		goodsNameTxt.setText(goodsName);
		goodsPriceTxt.setText(df.format(price));
		providerTxt.setText(cp);
		totalPriceTxt.setText(df.format(price));
	}

	/**
	 * @描述： 初始化进控件，并对控件设置监听
	 */
	private void init() {
		backIv = (ImageView) findViewById(R.id.title_back);
		battery = (BatteryCharger) findViewById(R.id.battery_charge);
		userInfoMoreIv = (ImageView) findViewById(R.id.user_info_more);
		exchangeBtn = (Button) findViewById(R.id.exchange_btn);
		cashOutBtn = (Button) findViewById(R.id.tixian_btn);
		cashOutBtn.setVisibility(View.GONE);
		userInfo = (RelativeLayout) findViewById(R.id.user_info);
		exchangeNumEdt = (EditText) findViewById(R.id.exchange_goods_num);
		userNameTv = (TextView) findViewById(R.id.user_name);
		awardNumTv = (TextView) findViewById(R.id.user_award_num);
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		userNameTv.setText(SharedPreferncesUtil.getNickName(this));
		exchangeNumEdt.setText("1");
		goodsNum = Integer.parseInt(exchangeNumEdt.getText().toString());
		exchangeNumEdt.setSelection(exchangeNumEdt.getText().toString()
				.length());

		addBtn = (Button) findViewById(R.id.goods_num_add);
		reduceBtn = (Button) findViewById(R.id.goods_num_reduce);
		sureBtn = (Button) findViewById(R.id.exchange_sure);
		cancleBtn = (Button) findViewById(R.id.exchange_cancle);

		goodsNameTxt = (TextView) findViewById(R.id.goods_name_tv);
		goodsPriceTxt = (TextView) findViewById(R.id.goods_price_tv);
		providerTxt = (TextView) findViewById(R.id.provider_tv);
		totalPriceTxt = (TextView) findViewById(R.id.total_price_tv);

		if (ChargeApplication.isBoxConnected) {
			battery.setVisibility(View.VISIBLE);
			battery.startChargerAnim();
		}

		backIv.setOnClickListener(this);
		exchangeBtn.setOnClickListener(this);
		cashOutBtn.setOnClickListener(this);
		// userInfo.setOnClickListener(this);
		addBtn.setOnClickListener(this);
		reduceBtn.setOnClickListener(this);
		sureBtn.setOnClickListener(this);
		cancleBtn.setOnClickListener(this);
		userInfoMoreIv.setOnClickListener(this);
		userNameTv.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;
		case R.id.user_info_more:
			Intent intent = new Intent(this, CenterActivity.class);
			startActivity(intent);
			break;
		case R.id.user_name:
			Intent intent1 = new Intent(this, ModifyNickNameActivity.class);
			intent1.putExtra("nickname", userNameTv.getText().toString());
			startActivity(intent1);
			break;
		case R.id.exchange_btn:
			Intent it = new Intent(this, ScanActivity.class);
			startActivity(it);
			break;
		case R.id.tixian_btn:
			Intent ite = new Intent(this, CashOutActivity.class);
			startActivity(ite);
			break;
		case R.id.user_info:
			Intent its = new Intent(this, CenterActivity.class);
			startActivity(its);
			break;
		case R.id.goods_num_add:
			goodsNum += 1;
			totalPriceTxt.setText(df.format(goodsNum * price));
			exchangeNumEdt.setText("" + goodsNum);
			exchangeNumEdt.setSelection(exchangeNumEdt.getText().toString()
					.length());
			break;
		case R.id.goods_num_reduce:
			if (goodsNum > 1) {
				goodsNum -= 1;
			}
			totalPriceTxt.setText(df.format(goodsNum * price));
			exchangeNumEdt.setText("" + goodsNum);
			exchangeNumEdt.setSelection(exchangeNumEdt.getText().toString()
					.length());
			break;
		case R.id.exchange_sure:
			String authKey = ChargeApplication.getInitInfo().get("AuthKey");
			if (TextUtils.isEmpty(authKey) || authKey == null) {
				ToastUtils.showShort(this, "正在获取用户初始化信息，请稍后重试");
				clientInit();
				return;
			}
			userExchange(authKey);
			break;
		case R.id.exchange_cancle:
			finish();
			break;
		}
	}

	/**
	 * @描述：
	 * @param authKey
	 */
	private void userExchange(String authKey) {
		if (NetUtils.isConnected(this)) {
			request.getRequestData(mHandler, Constant.SUBMIT_GOODS_ORDER,
					"AuthKey", authKey, "GoodsID", goodsId, "MerID", "0",
					"Count", goodsNum + "", "Remark", "");
		} else {
			ToastUtils.showShort(this, "兑换操作需要连接网络");
		}
	}

}
